﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Store;
using SIG.Model;
using SIG.Model.Enums;
using SIG.Model.Store;
using SIG.Resources;
using SIG.Resources.Admin;
using SIG.Service;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Store;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class GoodsController : BaseController
    {
        private readonly IGoodsCategoryService _goodsCategoryService;
        private readonly IGoodsService _goodsService;
        private readonly IPageMetaService _pageMetaService;
        private IMapper _mapper;
        public GoodsController(IGoodsService goodsService, IGoodsCategoryService goodsCategoryService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _goodsService = goodsService;
            _goodsCategoryService = goodsCategoryService;
            _pageMetaService = pageMetaService;
            _mapper = mapper;


        }

        // GET: Admin/Pages
        public ActionResult Index(int? page, int? categoryId, string keyword)
        {
            var goodsListVM = new GoodsListVM();

            if(categoryId!=null)
                goodsListVM.CategoryId = (int)categoryId;

            goodsListVM.Keyword = keyword;
            goodsListVM.PageIndex = (page ?? 1) - 1;
            goodsListVM.PageSize = SettingsManager.Store.PageSize;
            int totalCount;
            var goodslist = _goodsService.GetPagedElements(goodsListVM.PageIndex, goodsListVM.PageSize, goodsListVM.Keyword, goodsListVM.CategoryId, out totalCount);
            var categoryVMList = _mapper.Map<List<Goods>, List<GoodsVM>>(goodslist);
            goodsListVM.TotalCount = totalCount;

            goodsListVM.Goods = new StaticPagedList<GoodsVM>(categoryVMList, goodsListVM.PageIndex + 1, goodsListVM.PageSize, goodsListVM.TotalCount); ;

            var categoryList = _goodsCategoryService.GetAll().OrderByDescending(c=>c.Importance).ToList();
            var categories = new SelectList(categoryList, "Id", "Title");
            ViewBag.Categories = categories;

            ViewBag.PageSizes = new SelectList(Site.PageSizes());

            return View(goodsListVM);

        }

     

        // GET: Admin/Pages/Create
        [HttpGet]
        public ActionResult Create()
        {
            GoodsIM goods = new GoodsIM
            {
                Active = true              
            };

            var categoryList = _goodsCategoryService.GetAll().OrderByDescending(c => c.Importance).ToList();
            var categories = new SelectList(categoryList, "Id", "Title");
            ViewBag.Categories = categories;

            return View(goods);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public JsonResult Create([Bind(Include = "Id,Name,Description,FullDescription,CategoryId,Thumbnail,Price,Active,SEODescription,Keywords")] GoodsIM goods)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                var newGoods = _mapper.Map<GoodsIM, Goods>(goods);

                _goodsService.Create(newGoods);

                if (!string.IsNullOrEmpty(goods.Keywords) || !string.IsNullOrEmpty(goods.SEODescription))
                {
                    var pageMeta = new PageMeta()
                    {
                        ObjectId = newGoods.Id.ToString(),
                        Keyword = goods.Keywords.Replace('，', ','),
                        Description = goods.SEODescription,
                        ModelType = ModelType.GOODS
                    };
                    _pageMetaService.Create(pageMeta);
                }

                AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Goods));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }

        public ActionResult Edit(int id)
        {

            var goods = _goodsService.GetById(id);
            if (goods == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);
            }

            var editGoods = _mapper.Map<Goods, GoodsIM>(goods);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.GOODS, editGoods.Id.ToString());
            if (pageMeta != null)
            {
                editGoods.Keywords = pageMeta.Keyword;
                editGoods.SEODescription = pageMeta.Description;
            }

            var categoryList = _goodsCategoryService.GetAll().OrderByDescending(c => c.Importance).ToList();
            var categories = new SelectList(categoryList, "Id", "Title");
            ViewBag.Categories = categories;

            return View(editGoods);

           
        }



        [HttpPost]
        [ValidateAntiForgeryToken]

        public ActionResult Edit([Bind(Include = "Id,Name,Description,FullDescription,CategoryId,Thumbnail,Price,Active,SEODescription,Keywords")] GoodsIM goods)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);

            }

            try
            {
                var editGoods = _mapper.Map<GoodsIM, Goods>(goods);

                _goodsService.Update(editGoods);

                var pageMeta = _pageMetaService.GetPageMeta(ModelType.GOODS, editGoods.Id.ToString());
                pageMeta = pageMeta ?? new PageMeta();


                if (!string.IsNullOrEmpty(goods.Keywords) || !string.IsNullOrEmpty(goods.SEODescription))
                {
                    pageMeta.ObjectId = goods.Id.ToString();
                    pageMeta.Keyword = goods.Keywords.Replace('，', ',');
                    pageMeta.Description = goods.SEODescription;
                    pageMeta.ModelType = ModelType.GOODS;

                    if (pageMeta.Id > 0)
                    {
                        _pageMetaService.Update(pageMeta);
                    }
                    else
                    {
                        _pageMetaService.Create(pageMeta);
                    }
                }

                AR.SetSuccess(string.Format(Messages.AlertUpdateSuccess, EntityNames.Goods));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {
            var goods = _goodsService.GetById(id);
            if (goods != null)
            {
                goods.Active = !goods.Active;
                _goodsService.Update(goods);

                AR.SetSuccess(String.Format(Messages.AlertActionSuccess, EntityNames.Goods));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            AR.Setfailure(String.Format(Messages.AlertActionFailure, EntityNames.Goods));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }



        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {
            var category = _goodsService.GetById(id);
            if (category != null)
            {
                _goodsService.Delete(category);

                AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Goods));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            AR.Setfailure(String.Format(Messages.AlertDeleteFailure, EntityNames.Goods));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }
        //[AllowAnonymous]
        //public JsonResult IsSeoNameUnique(string seoName, int? Id)
        //{
        //    return !IsExist(seoName, Id)
        //        ? Json(true, JsonRequestBehavior.AllowGet)
        //        : Json(false, JsonRequestBehavior.AllowGet);
        //}
        //[AllowAnonymous]
        //public bool IsExist(string seoName, int? id)
        //{
        //    var wType = _goodsService.GetAll().Where(w => w.SeoName == seoName);
        //    if (id > 0)
        //    {
        //        wType = wType.Where(w => w.Id != id);
        //    }

        //    if (wType.Count() > 0)
        //        return true;

        //    return false;
        //}
    }
}